/*
 * SQLeonardo :: java database frontend
 * Copyright (C) 2004 nickyb@users.sourceforge.net
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

package com.sqleo.environment.ctrl.editor;

import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;

import com.sqleo.common.gui.CustomLineBorder;
import com.sqleo.querybuilder.QueryBuilder;
import com.sqleo.querybuilder.syntax.QueryTokens;
import com.sqleo.querybuilder.syntax.SQLFormatter;


public class BuildInsert extends BuildBasePane
{
	private BuildBaseEntity entity;
	
	public BuildInsert(_BuildOwner owner)
	{
		super(owner);
	}

	void initComponents()
	{
		entity = new BuildBaseEntity(this);
		entity.setBorder(new CustomLineBorder(true,true,false,false));
		
		JScrollPane scroll = new JScrollPane(entity);
		scroll.setBorder(new TitledBorder(" values "));
		setComponentCenter(scroll);
	}

	void add(QueryTokens.Column column)
	{
		entity.addField(SQLFormatter.ensureQuotes(column.getName(),owner.getIdentifierQuoteString(),!QueryBuilder.useAlwaysQuote));
	}
	
	void clear()
	{
		entity.removeRows();
	}

	public String getSyntax()
	{
		StringBuffer fields = new StringBuffer();
		StringBuffer values = new StringBuffer();
		
		if(entity!=null)
		{
			for(int i=0; i<entity.getRowCount(); i++)
			{
				if(entity.isCellEditable(i,2))
				{
					fields.append(entity.getValueAt(i,1).toString()+", ");
					values.append((entity.getValueAt(i,2)!=null?entity.getValueAt(i,2).toString():null)+", ");
				}
			}
			
			if(fields.length()>0) fields.deleteCharAt(fields.length()-2);
			if(values.length()>0) values.deleteCharAt(values.length()-2);
			
			return "INSERT INTO " + owner.getTable() + " (" + fields.toString().trim() + ") VALUES (" + values.toString().trim() + ")";
		}
		
		return "INSERT INTO";
	}
}
